package com.learn.rocketmq.simple;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;

/**
 * 生产者
 *
 * @date 2021/8/16
 */
public class Producer {

    private final String producerGroupName;
    private final String nameServer;
    private DefaultMQProducer producer;

    public Producer(String producerGroupName, String nameServer) {
        System.out.println("Producer constructor ...");
        this.producerGroupName = producerGroupName;
        this.nameServer = nameServer;
    }

    public DefaultMQProducer getProducer() {
        return producer;
    }

    public void init() throws MQClientException {
        System.out.println("Producer init s ...");

        // 创建一个消息生产者，并设置一个消息生产者组
        producer = new DefaultMQProducer(producerGroupName);
        // 指定 NameServer 地址
        producer.setNamesrvAddr(nameServer);
        // 初始化 Producer，整个应用生命周期内只需要初始化一次
        producer.start();

        System.out.println("Producer init e ...");
    }

    public void destroy() {
        System.out.println("Producer destroy s ...");

        // 销毁
        producer.shutdown();

        System.out.println("Producer destroy e ...");
    }
}
